package org.example.mqtt.demo1.message;

import org.example.mqtt.demo1.config.MqttConfig;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.support.MessageBuilder;

import javax.annotation.Resource;

/**
 * Created by way on 2017/12/22.
 */
public class MqttReceiver implements MessageHandler {

    @Resource
    private MqttConfig mqttConfig;

    @Resource
    private MqttSender mqttSender;

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        System.out.println("receive msg:\n " + message.getPayload());
        if (mqttConfig.isMqttServerFlag()) {
            //如果是服務器，且是客戶端發送的消息，將消息返回
            String topic = getClientTopic(message.getHeaders());
            //點播回去
            Message severMeg = MessageBuilder.withPayload("server convert " + message.getPayload()).setHeader(MqttHeaders.TOPIC, topic).build();
            mqttSender.send(severMeg);
        }

    }

    private String getClientTopic(MessageHeaders headers) {
        String topic = headers.get(MqttHeaders.TOPIC, String.class);
        return MqttConfig.mqttClientTopicRoot + topic.substring(topic.indexOf("/"));
    }
}
